Understanding Logical Operators in Python
Course: Python Training
Topic: Understanding Logical Operators in Python
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Free Course Demo
Website: Visit JustAcademy
1. Introduction to Logical Operators in Python
Logical operators in Python are used to combine multiple conditions or reverse the truth value of a condition. They help programs make decisions based on whether one or more expressions evaluate to true or false.
Logical operators are frequently used with conditional statements such as if, elif, and else, as well as with loops and validation logic. They are useful for checking user input, verifying eligibility, controlling access, filtering information, and handling business rules.
For example, an application may allow a user to log in only when the username is correct and the password is valid. Another program may provide a discount when a customer is a member or has purchased more than a specified amount.
Python provides three primary logical operators:
| Operator |
Purpose |
Example |
and |
Evaluates to a truthy result only when both operands are truthy. |
age >= 18 and has_id |
or |
Evaluates to a truthy result when at least one operand is truthy. |
is_member or has_coupon |
not |
Reverses the truth value of an expression. |
not is_blocked |
2. Learning Objectives
After studying this topic, you will be able to:
- Understand the purpose of logical operators in Python.
- Differentiate between
and, or, and not.
- Use truth tables to understand logical expressions.
- Combine multiple conditions in a single expression.
- Apply logical operators in conditional statements and loops.
- Understand short-circuit evaluation.
- Recognize the difference between Boolean results and other truthy or falsy values.
- Identify common mistakes and write readable logical expressions.
3. Understanding Boolean Values
Before learning logical operators, it is important to understand Boolean values. Python has two Boolean constants: True and False. They represent logical truth and logical falsity.
is_active = True
is_deleted = False
print(is_active)
print(is_deleted)
print(type(is_active))
Output:
True
False
<class 'bool'>
Comparisons usually produce Boolean values. For example, 10 > 5 evaluates to True, while 10 < 5 evaluates to False.
print(10 > 5)
print(10 == 5)
print(7 != 3)
Output:
True
False
True
Logical operators can combine these comparison results to create more complex conditions.
4. The and Operator
The and operator combines two expressions. For ordinary Boolean operands, the complete expression is True only when both expressions are True.
4.1 Syntax
condition1 and condition2
4.2 Truth Table for and
| Condition 1 |
Condition 2 |
Result |
| True |
True |
True |
| True |
False |
False |
| False |
True |
False |
| False |
False |
False |
4.3 Example with Boolean Values
print(True and True)
print(True and False)
print(False and True)
print(False and False)
Output:
True
False
False
False
4.4 Example with Comparison Operators
age = 25
has_license = True
can_drive = age >= 18 and has_license
print(can_drive)
Output:
True
Explanation: The first condition checks whether the person is at least 18 years old. The second checks whether the person has a license. Both conditions must be true for can_drive to be true in this simplified example.
4.5 Practical Example: Login Validation
username_correct = True
password_correct = True
if username_correct and password_correct:
print("Login successful")
else:
print("Invalid username or password")
Output:
Login successful
If either variable is False, the complete condition evaluates to false, and the failure message is printed. Real authentication systems must validate credentials securely rather than relying on simple Boolean variables.
4.6 When to Use and
- When all required conditions must be satisfied.
- When validating a value against a range.
- When checking several eligibility requirements.
- When combining user-input validation rules.
For example, a score is considered valid when it is at least zero and no greater than one hundred:
score = 85
if score >= 0 and score <= 100:
print("Valid score")
else:
print("Invalid score")
5. The or Operator
The or operator combines conditions when at least one condition must be true. For Boolean operands, the result is false only when both operands are false.
5.1 Syntax
condition1 or condition2
5.2 Truth Table for or
| Condition 1 |
Condition 2 |
Result |
| True |
True |
True |
| True |
False |
True |
| False |
True |
True |
| False |
False |
False |
5.3 Example with Boolean Values
print(True or True)
print(True or False)
print(False or True)
print(False or False)
Output:
True
True
True
False
5.4 Example with Conditions
is_member = False
has_coupon = True
if is_member or has_coupon:
print("Discount available")
else:
print("No discount available")
Output:
Discount available
Explanation: The customer receives the discount in this example because having a coupon is sufficient, even though the customer is not a member.
5.5 Practical Example: Weekend Check
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend")
else:
print("It is a weekday")
Output:
It is the weekend
5.6 When to Use or
- When any one of several conditions is sufficient.
- When checking for multiple acceptable values.
- When providing alternative ways to qualify for an action.
- When checking whether an input matches one of several permitted choices.
6. The not Operator
The not operator reverses the truth value of an expression. If an expression evaluates to True, applying not makes it False. If the expression evaluates to False, applying not makes it True.
6.1 Syntax
not condition
6.2 Truth Table for not
| Condition |
Result of not |
| True |
False |
| False |
True |
6.3 Example with Boolean Values
print(not True)
print(not False)
Output:
False
True
6.4 Example with a Comparison
temperature = 15
print(not temperature > 30)
Output:
True
Explanation: The comparison temperature > 30 is false because 15 is not greater than 30. The not operator reverses that result to true.
6.5 Practical Example: Account Status
is_blocked = False
if not is_blocked:
print("Account access allowed")
else:
print("Account access denied")
Output:
Account access allowed
This pattern is useful when a condition is easier to express as the opposite of a state, such as “not blocked” or “not empty.” For security-sensitive applications, the actual permission and authentication rules must still be validated correctly.
7. Comparing the Three Logical Operators
| Operator |
Meaning |
True for Boolean operands when |
Example |
and |
Both conditions must hold |
Both operands are true |
True and False → False |
or |
At least one condition must hold |
At least one operand is true |
True or False → True |
not |
Negates a condition |
The original operand is false |
not False → True |
A simple way to remember them is:
and: All conditions must be true.
or: At least one condition must be true.
not: Reverse the truth value.
8. Combining Multiple Logical Operators
Python allows multiple logical operators to be combined in one expression. This makes it possible to represent more detailed rules, but it is important to understand operator precedence and use parentheses where they improve clarity.
8.1 Combining and and or
age = 22
is_student = True
has_discount_card = False
if age < 18 or (is_student and has_discount_card):
print("Special discount available")
else:
print("Standard price applies")
Output:
Standard price applies
Explanation: The first condition is false because the age is not below 18. The second condition is also false because the student status is true but the discount-card status is false. Therefore, the overall expression is false.
8.2 Using Parentheses for Clarity
Parentheses group conditions and make the intended logic easier to understand. In Python, not has higher precedence than and, and and has higher precedence than or.
a = True
b = False
c = True
result = a or b and c
print(result)
result_with_parentheses = (a or b) and c
print(result_with_parentheses)
Output:
True
True
In this example, both expressions happen to produce true. To see why grouping matters, consider another example:
a = False
b = True
c = False
print(a or b and c)
print((a or b) and c)
Output:
False
False
Here, both results are also false, but the expressions are evaluated differently. A clearer example showing different results is:
a = True
b = False
c = False
print(a or b and c)
print((a or b) and c)
Output:
True
False
In the first expression, b and c is evaluated before or, so the result is True. In the second expression, the parenthesized expression a or b is evaluated first, and its result is then combined with c using and.
9. Logical Operators with Conditional Statements
Logical operators are commonly used in if statements to control which block of code executes.
9.1 Example: Exam Eligibility
attendance = 85
marks = 72
if attendance >= 75 and marks >= 40:
print("Eligible to pass")
else:
print("Does not meet the requirements")
Output:
Eligible to pass
Both requirements must be met: attendance must be at least 75 percent, and marks must be at least 40.
9.2 Example: Multiple Acceptable Login Methods
login_method = "email"
if login_method == "email" or login_method == "phone":
print("Supported login method")
else:
print("Unsupported login method")
Output:
Supported login method
9.3 Example: Checking a Negative Condition
is_maintenance_mode = False
if not is_maintenance_mode:
print("Website is available")
else:
print("Website is temporarily unavailable")
Output:
Website is available
10. Logical Operators with Loops
Logical operators can also control the repetition of loops. A loop can continue while several conditions are true or until one of multiple stopping conditions becomes true.
10.1 Using and in a while Loop
number = 1
while number <= 5 and number > 0:
print(number)
number += 1
Output:
1
2
3
4
5
The loop continues while the number is no greater than five and greater than zero.
10.2 Using or in a Loop
attempts = 0
success = False
while attempts < 3 or success:
print("Checking attempt:", attempts + 1)
attempts += 1
if attempts == 3:
success = False
break
Output:
Checking attempt: 1
Checking attempt: 2
Checking attempt: 3
This example demonstrates the syntax, but the condition is not a typical retry rule because or success would allow the loop to continue even after the attempt limit if success were true. For a real retry loop, a clearer condition is usually:
attempts = 0
success = False
while attempts < 3 and not success:
attempts += 1
print("Attempt:", attempts)
# Replace this with the actual operation.
success = False
if not success:
print("Maximum attempts reached")
The second example expresses the usual intention: continue while attempts remain and the operation has not succeeded.
11. Short-Circuit Evaluation
Python uses short-circuit evaluation with the and and or operators. This means Python may skip evaluating the second operand when the first operand already determines the outcome.
11.1 Short-Circuiting with and
If the first operand of and is falsy, Python does not need to evaluate the second operand because the overall result is already determined.
def check_status():
print("Function executed")
return True
result = False and check_status()
print(result)
Output:
False
The function is not executed, so the message inside it is not printed.
11.2 Short-Circuiting with or
If the first operand of or is truthy, Python does not need to evaluate the second operand.
def check_status():
print("Function executed")
return True
result = True or check_status()
print(result)
Output:
True
The function is not executed because the first operand already determines that the or expression is truthy.
11.3 Why Short-Circuit Evaluation Is Useful
- It can avoid unnecessary calculations or function calls.
- It can prevent an operation from running when a prerequisite is not met.
- It helps write safe checks when the order of conditions is chosen carefully.
For example, the following code checks that a list is not empty before accessing its first element:
items = [10, 20, 30]
if items and items[0] > 5:
print("The first item is greater than five")
Output:
The first item is greater than five
If items were empty, the second condition would not be evaluated. This prevents an IndexError from accessing items[0].
12. Truthy and Falsy Values
Logical operators do not work only with the Boolean values True and False. Python also evaluates other objects according to their truth value.
Common falsy values include:
False
None
- Numeric zero, such as
0, 0.0, and 0j
- Empty strings, such as
""
- Empty collections, such as
[], (), {}, and set()
Most other values are truthy, including non-empty strings, non-empty collections, and non-zero numbers.
print(bool(0))
print(bool(10))
print(bool(""))
print(bool("Python"))
print(bool([]))
print(bool([1, 2]))
Output:
False
True
False
True
False
True
The built-in bool() function converts a value to its Boolean truth value.
13. Logical Operators Can Return Non-Boolean Values
An important Python feature is that and and or do not always return the Boolean values True or False. They return one of their operands according to truthiness.
13.1 Return Behavior of and
The and operator returns the first falsy operand, or the last operand if all operands are truthy.
print(0 and 10)
print("Python" and 25)
print("Hello" and "World")
Output:
0
25
World
In the first expression, zero is falsy, so Python returns 0. In the second and third expressions, the first operand is truthy, so the second operand is returned.
13.2 Return Behavior of or
The or operator returns the first truthy operand, or the last operand if all operands are falsy.
print(0 or 10)
print("" or "Default")
print(None or "No value provided")
Output:
10
Default
No value provided
This behavior is often used to provide fallback values. However, it can be unsuitable when valid values such as zero or an empty string must be preserved.
13.3 Choosing a Default Value Carefully
quantity = 0
# This replaces zero because zero is falsy.
display_quantity = quantity or 1
print(display_quantity)
# This preserves zero and replaces only None.
display_quantity = 1 if quantity is None else quantity
print(display_quantity)
Output:
1
0
Use or for a fallback when any falsy value should trigger the default. If only None should trigger the default, check explicitly with is None.
14. Difference Between Logical and Comparison Operators
Comparison operators compare values and generally produce Boolean results. Logical operators combine or reverse truth values, although and and or can return the original operand.
| Operator Category |
Examples |
Purpose |
| Comparison |
==, !=, >, <, >=, <= |
Compare two values. |
| Logical |
and, or, not |
Combine or reverse truth values. |
age = 21
has_ticket = True
# Comparison expressions
print(age >= 18)
print(has_ticket)
# Logical expression
print(age >= 18 and has_ticket)
Output:
True
True
True
15. Operator Precedence
Operator precedence determines the order in which parts of an expression are evaluated. For logical operators, the order from highest to lowest precedence is:
not
and
or
result = not False and False or True
print(result)
Output:
True
Explanation:
not False becomes True.
True and False becomes False.
False or True becomes True.
Although Python follows these precedence rules, parentheses are recommended when they make complicated conditions easier to read.
16. Common Mistakes When Using Logical Operators
16.1 Using and When or Is Required
Incorrect:
day = "Saturday"
if day == "Saturday" and day == "Sunday":
print("Weekend")
The condition can never be true because a single string cannot equal both values at the same time.
Correct:
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
16.2 Repeating a Variable Incorrectly in a Range Check
Incorrect:
age = 25
if age >= 18 and <= 60:
print("Eligible")
This is invalid Python syntax because the second comparison has no left operand.
Correct:
age = 25
if age >= 18 and age <= 60:
print("Eligible")
Python also supports chained comparisons, which can make range checks shorter:
if 18 <= age <= 60:
print("Eligible")
16.3 Forgetting Operator Precedence
Complex conditions can produce unexpected results if the intended grouping is unclear.
is_admin = False
is_manager = True
is_active = True
if (is_admin or is_manager) and is_active:
print("Access condition satisfied")
Parentheses make it clear that the user must be an administrator or manager and must also be active.
16.4 Using is Instead of ==
Use == to compare values. The is operator checks object identity and is commonly used for comparisons with None.
status = "active"
print(status == "active")
print(status is None)
Output:
True
False
16.5 Assuming and and or Always Return Booleans
result = "" or "Guest"
print(result)
print(type(result))
Output:
Guest
<class 'str'>
Here, or returns a string rather than a Boolean value.
16.6 Writing Unnecessarily Complicated Conditions
Prefer clear conditions over expressions that are difficult to understand. If a condition contains many operators, consider assigning meaningful intermediate variables.
is_old_enough = age >= 18
has_required_document = True
if is_old_enough and has_required_document:
print("Requirements satisfied")
17. Practical Real-World Examples
17.1 Age Eligibility
age = 20
if age >= 18:
print("Eligible to register")
else:
print("Not eligible to register")
17.2 Discount Eligibility
purchase_amount = 1500
is_member = True
if purchase_amount >= 1000 or is_member:
print("Discount available")
else:
print("No discount available")
17.3 Form Validation
name = "Aarav"
email = "[email protected]"
if name != "" and email != "":
print("Required fields are filled")
else:
print("Please complete the required fields")
This is a basic example. Real email validation requires additional checks beyond verifying that the string is not empty.
17.4 Checking a Temperature Range
temperature = 24
if temperature >= 18 and temperature <= 30:
print("Temperature is within the desired range")
else:
print("Temperature is outside the desired range")
17.5 Checking Whether a Collection Is Empty
cart = []
if not cart:
print("Your cart is empty")
else:
print("Items are available in your cart")
An empty list is falsy, so not cart evaluates to true.
17.6 Access Rules Using Multiple Conditions
is_employee = True
has_permission = True
is_suspended = False
if is_employee and has_permission and not is_suspended:
print("Access granted")
else:
print("Access denied")
Output:
Access granted
This example demonstrates how multiple requirements can be combined. Actual access-control decisions should be based on trusted authentication and authorization data.
18. Best Practices for Logical Operators
- Use
and when every required condition must be satisfied.
- Use
or when any one of several conditions is sufficient.
- Use
not to express negative conditions clearly.
- Use parentheses to make complex expressions easier to understand.
- Use meaningful variable names for important conditions.
- Understand short-circuit evaluation before placing function calls inside logical expressions.
- Use explicit checks when zero, empty strings, or empty collections are valid values.
- Use chained comparisons for readable numeric ranges, such as
0 <= score <= 100.
- Test boundary values such as zero, the minimum allowed value, and the maximum allowed value.
- Keep security-critical checks explicit and validate data on the trusted side of an application.
19. Practice Exercises
Exercise 1: Use the and Operator
Create two variables, age and has_permission. Print “Allowed” only when the age is at least 18 and permission is true.
Exercise 2: Use the or Operator
Create a variable named day. Print “Holiday” when the day is either Saturday or Sunday.
Exercise 3: Use the not Operator
Create a variable named is_closed. Print “Open” when the variable is false.
Exercise 4: Validate a Score
Write a program that checks whether a score is between 0 and 100, inclusive.
Exercise 5: Check Login Conditions
Create Boolean variables for a correct username, a correct password, and an active account. Print “Login permitted” only when all three requirements are satisfied.
Exercise 6: Check an Empty List
Create an empty list and use a logical operator to display a message when the list has no items.
Exercise 7: Understand Short-Circuiting
Create a function that prints a message when it runs. Use False and function() and True or function() to observe when the function executes.
20. Mini Project: Student Eligibility Checker
Objective: Build a simple program that checks whether a student meets basic eligibility requirements using logical operators.
Requirements:
- The student must have attendance of at least 75 percent.
- The student must have a score of at least 40.
- The score must not exceed 100.
- The program must display a suitable result.
attendance = 82
score = 68
valid_score = 0 <= score <= 100
attendance_ok = attendance >= 75
score_ok = score >= 40
if valid_score and attendance_ok and score_ok:
print("Student is eligible")
elif not valid_score:
print("Invalid score")
else:
print("Student is not eligible")
Output:
Student is eligible
Project explanation: The program first defines the validation conditions. It then combines the conditions with and to determine whether the student meets all requirements. The not operator is used to identify an invalid score.
Extension tasks:
- Ask the user to enter attendance and score using
input().
- Convert the entered values into numbers using
float() or int().
- Handle invalid input with
try and except.
- Add a separate condition for outstanding performance.
- Test the program with scores of -1, 0, 39, 40, 100, and 101.
21. Interview Questions and Answers
Q1. What are logical operators in Python?
Answer: Logical operators combine conditions or reverse truth values. Python provides and, or, and not.
Q2. What is the difference between and and or?
Answer: With Boolean operands, and is true only when both operands are true. or is true when at least one operand is true.
Q3. What does the not operator do?
Answer: It reverses the truth value of an expression. For example, not True evaluates to False.
Q4. What is short-circuit evaluation?
Answer: Short-circuit evaluation means Python stops evaluating a logical expression when the result is already determined. For example, False and expression does not evaluate the second operand.
Q5. Do and and or always return Boolean values?
Answer: No. They return one of their operands based on truthiness. For example, "" or "Guest" returns the string "Guest".
Q6. What is the precedence of logical operators?
Answer: The precedence from highest to lowest is not, and, then or.
Q7. How do you check whether a number is within a range?
Answer: You can use a chained comparison such as 0 <= score <= 100.
Q8. What is a falsy value?
Answer: A falsy value evaluates to false in a Boolean context. Examples include False, None, zero, an empty string, and an empty list.
Q9. How can you check whether a list is empty?
Answer: Use if not items: to check whether a list or another collection is empty.
Q10. Why are parentheses useful in logical expressions?
Answer: Parentheses make the intended grouping explicit, improve readability, and help prevent errors when several logical operators are combined.
22. Quick Revision Checklist
and combines conditions that must all be true.
or combines alternatives where at least one must be true.
not reverses a truth value.
- Comparison expressions often produce
True or False.
- Python supports truthy and falsy values beyond Boolean constants.
and and or can return operands instead of Boolean values.
- Short-circuit evaluation can skip unnecessary evaluation.
- Logical precedence is
not, then and, then or.
- Parentheses help make complex expressions clearer.
- Test logical conditions with both typical and boundary values.
23. Conclusion
Logical operators are an essential part of Python programming because they allow developers to combine conditions, implement decision-making rules, validate data, and control program flow. The and operator is useful when all conditions must be satisfied, or is useful when one of several alternatives is sufficient, and not reverses the truth value of an expression.
Understanding truthy and falsy values, short-circuit evaluation, and operator precedence helps you write accurate and readable programs. Practice these operators with conditional statements, loops, and real-world validation examples to build a strong foundation in Python programming.
Continue Learning with JustAcademy
Explore more Python programming concepts and practical training through the following links: